<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row :gutter="24">
          <el-col v-bind="grid"><div class="grid-content bg-purple" /></el-col>
        </el-row>
        <el-button size="small" type="primary" @click="addDialogVisible = true"
          >添加身份</el-button
        >
      </div>
      <el-table
        border
        stripe
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="small"
      >
        <el-table-column prop="roleId" label="ID" min-width="150" />
        <el-table-column prop="roleName" label="身份名称" min-width="150" />
        <el-table-column prop="status" label="是否显示" min-width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              :active-value="1"
              :inactive-value="0"
              @change="onchangeIsShow(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="200" />
        <el-table-column label="操作" min-width="300" fixed="right">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              type="warning"
              size="small"
              @click="onEdit(scope.row.roleId)"
            ></el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="small"
              @click="handleDelete(scope.row.roleId)"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleMenuTreeList(scope.row.roleId)"
              >分配菜单</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleResourceCategoryTreeList(scope.row.roleId)"
              >分配资源</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[5, 10, 15, 20]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!-- 分配菜单 -->
    <el-dialog
      title="分配菜单"
      @close="resRoleDialogClosed"
      :visible.sync="resDialogVisible"
      width="50%"
    >
      <el-form :model="resRuleForm" ref="resRuleFormRef" label-width="100px">
        <el-form-item label="分配资源 ：">
          <el-tree
            :data="resRightsList"
            :props="resTreeProps"
            ref="resTreeRef"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="resDefKeys"
          ></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配资源"
      @close="muneRoleDialogClosed"
      :visible.sync="muneDialogVisible"
      width="50%"
    >
      <el-form :model="muneRuleForm" ref="muneRuleFormRef" label-width="100px">
        <el-form-item label="分配菜单 ：">
          <el-tree
            :data="muneRightsList"
            :props="muneTreeProps"
            ref="muneTreeRef"
            show-checkbox
            node-key="menuId"
            default-expand-all
            :default-checked-keys="muneDefKeys"
          ></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="muneDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="menuDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加身份对话框 -->
    <el-dialog
      title="添加身份"
      @close="addRoleDialogClosed"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addRuleFormRef"
        label-width="100px"
      >
        <el-form-item label="身份名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改身份对话框 -->
    <el-dialog
      title="添加身份"
      @close="editRoleDialogClosed"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        :model="editRuleForm"
        :rules="addRules"
        ref="editRuleFormRef"
        label-width="100px"
      >
        <el-form-item label="身份名称" prop="roleName">
          <el-input v-model="editRuleForm.roleName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  resourceCategoryUpdateTreeListApi,
  resTreeListApi,
  menuDpdateTreeListApi,
  menuTreelistMenuApi,
  menuTreeListApi,
  treeListApi,
  menuRoleApi,
  getinfoApi,
  roleCreateApi,
  roleUpdateApi,
  roleDeleteApi,
  roleStatusApi,
} from "@/api/setting";
export default {
  name: "SystemRole",
  data() {
    return {
      //权限列表
      resRightsList: [],
      muneRightsList: [],
      //树形控件的属性绑定对象
      resTreeProps: {
        label: "name",
        children: "children",
      },
      muneTreeProps: {
        label: "menuName",
        children: "children",
      },
      //分配权限中默认选中节点ID值
      muneRoleId: "",
      resRoleId: "",
      resDefKeys: [],
      muneDefKeys: [],
      // 添加身份管理的表单
      addRuleForm: {},
      editRuleForm: {},
      resRuleForm: {},
      muneRuleForm: {},
      addRules: {
        roleName: [
          { required: true, message: "请输入身份名称", trigger: "blur" },
        ],
      },
      // 添加身份管理对话框
      addDialogVisible: false,
      editDialogVisible: false,
      resDialogVisible: false,
      muneDialogVisible: false,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      tableData: {
        data: [],
        total: 0,
      },
      listLoading: true,
      tableFrom: {
        page: 1,
        limit: 5,
      },
    };
  },
  computed: {},
  mounted() {
    this.getList();
    this.getResTreeList();
    this.getMuneTreeList();
  },
  methods: {
    // 获取资源树
    getResTreeList() {
      treeListApi()
        .then((res) => {
          this.resRightsList = res.data;
        })
        .catch((message) => {
          this.$message.error(message);
        });
    },
    // 获取菜单树
    getMuneTreeList() {
      menuTreeListApi()
        .then((res) => {
          this.muneRightsList = res.data;
        })
        .catch((message) => {
          this.$message.error(message);
        });
    },
    // 分配菜单按钮
    handleMenuTreeList(id) {
      this.muneDefKeys = [];
      this.muneDialogVisible = true;
      this.muneRoleId = id;
      menuTreelistMenuApi(id)
        .then((res) => {
          if (res.data.length) {
            for (var i = 0; res.data.length > i; i++) {
              this.muneDefKeys[i] = res.data[i].menuId;
            }
            this.muneDefKeys = Array.from(this.muneDefKeys);
          }
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },

    // 分配菜单提交按钮
    menuDialogSubmit() {
      // 先获取到选中的id
      const DefKeys = [...this.$refs.muneTreeRef.getCheckedKeys()];
      console.log(DefKeys);
      menuDpdateTreeListApi(this.muneRoleId, DefKeys)
        .then(({ message }) => {
          this.$message.success(message);
          this.muneDialogVisible = false;
          this.getMuneTreeList();
        })
        .catch(({ message }) => {
          this.$message.error(message);
        });
    },

    // 分配资源按钮
    handleResourceCategoryTreeList(id) {
      this.resDefKeys = [];
      this.resRoleId = id;
      this.resDialogVisible = true;
      resTreeListApi(id)
        .then((res) => {
          console.log(res, "22222222222");
          if (res.data.length) {
            for (var i = 0; res.data.length > i; i++) {
              this.resDefKeys[i] = res.data[i].id;
            }
            this.resDefKeys = Array.from(new Set(this.resDefKeys));
          }
          console.log(this.resDefKeys, "111111");
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },
    // 分配资源提交按钮
    resDialogSubmit() {
      // 先获取到选中的id
      const DefKeys = [...this.$refs.resTreeRef.getCheckedKeys()];
      console.log(DefKeys);
      resourceCategoryUpdateTreeListApi(this.resRoleId, DefKeys)
        .then(({ message }) => {
          this.$message.success(message);
          this.resDialogVisible = false;
          this.getResTreeList();
        })
        .catch(({ message }) => {
          this.$message.error(message);
          this.resDialogVisible = false;
        });
    },
    addRoleDialogClosed() {
      this.$refs.addRuleFormRef.resetFields();
    },
    editRoleDialogClosed() {
      this.$refs.editRuleFormRef.resetFields();
    },
    resRoleDialogClosed() {
      this.$refs.resRuleFormRef.resetFields();
      this.resDefKeys = [];
      this.getResTreeList();
    },
    muneRoleDialogClosed() {
      this.$refs.muneRuleFormRef.resetFields();
      this.muneDefKeys = [];
      this.getMuneTreeList();
    },
    // 列表
    getList() {
      this.listLoading = true;
      menuRoleApi(this.tableFrom)
        .then((res) => {
          console.log(res, "获取列表");
          this.tableData.data = res.data;
          this.tableData.total = res.data.length;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    onchangeIsShow(row) {
      console.log(row);
      roleStatusApi(row.roleId, row.status)
        .then(({ message }) => {
          this.$message.success(message);
        })
        .catch(({ message }) => {
          this.$message.error(message);
        });
    },
    // 添加
    addDialogSubmit() {
      roleCreateApi(this.addRuleForm)
        .then((message) => {
          this.getList();
          this.$message.success(message);
          this.addDialogVisible = false;
        })
        .catch((message) => {
          this.$message.error(message);
          this.addDialogVisible = false;
        });
    },
    // 编辑按钮点击事件
    onEdit(id) {
      this.editDialogVisible = true;
      getinfoApi(id)
        .then((res) => {
          this.editRuleForm = res.data;
        })
        .catch((message) => {
          this.$message.error(message);
        });
    },
    // 编辑按钮对话框点击事件
    editDialogSubmit() {
      console.log(this.editRuleForm)
      roleUpdateApi(this.editRuleForm.roleId,this.editRuleForm)
        .then((message) => {
          this.$message.success(message);
          this.editDialogVisible = false;
          this.getList();
        })
        .catch((message) => {
          this.$message.error(message);
        });
    },
    // 删除按钮点击事件
    async handleDelete(id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该身份, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 如果用户确认了删除，则返回值为字符串：confirm
      // 如果用户取消了删除，则返回值为字符串：cancel
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        this.$message.info("已经取消了删除");
      } else {
        roleDeleteApi(id)
          .then(() => {
            this.$message.success("删除身份成功");
            // 删除成功后，更新数据
            this.getList();
          })
          .catch(() => {
            this.$message.error("删除身份失败！");
          });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.el-switch {
  width: 40px;
}
</style>
